package threadtest;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static threadtest.P.print;

/**
 * @author: mornd
 *
 * allOf 所有任务执行完
 * anyOf 有一个执行完即可
 */
public class CompletableFutureTest3 {
    static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5,
            20,
            10, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(1000));

    public static void main(String[] args) throws Exception {
        print("main start");

        CompletableFuture<Integer> c1 = CompletableFuture.supplyAsync(() -> {
            print("running c1");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//            int a = 1/0;
            return 101;
        }, threadPoolExecutor);
        CompletableFuture<Integer> c2 = CompletableFuture.supplyAsync(() -> {
            print("running c2");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 102;
        }, threadPoolExecutor);

        // 阻塞等待，如果c2执行完了，c1还没执行完，此时还不能打印c2，得等到c1执行完，不过此时c2有结果，打印c2就不用阻塞了
        // 执行所有get的打印时间=最大任务的执行时长
//        print(c1.get());
//        print(c2.get());

//        CompletableFuture.allOf(c1, c2).get(); // 手动调用各个get()
        CompletableFuture.allOf(c1, c2).join();

        // 有一个执行完即可
//        CompletableFuture.anyOf(c1, c2).join();

        print("main end");
    }
}
